package cn.tedu.common.pojo.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json工具类
 * 对象转换为Json
 * Json 转对象
 */
public class JsonUtils {

    /**
     * 定义对象转换工具 SpringBoot默认 jackson ObjectMapper
     * static 表示静态 jvm在加载的时候 会创建 还能保证只创建一个
     */
    private static final ObjectMapper
            objectMapper = new ObjectMapper();

    public static String toJson(Object object) {
        //没有必要每次调用toJson 都创建  ObjectMapper
        //占用jvm的内存空间
 /*       ObjectMapper
                objectMapper = new ObjectMapper();*/
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to convert object to JSON", e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert JSON to object", e);
        }
    }
}
